<template>
  <div class="wfull">
    <a-form :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
      <a-form-item label="公式名称" required>
        <ZgInput v-model="name"></ZgInput>
      </a-form-item>
      <a-form-item label="公式类型" required>
        <ZgEnum :width="120" v-model="cata" code="公式类型"></ZgEnum>
      </a-form-item>
      <a-form-item label="触发机制" required>
        <ZgEnum :width="120" v-model="triggerMode" code="公式触发机制"></ZgEnum>
      </a-form-item>
      <a-form-item label="公式内容" required>
        <ZgCodeMirror ref="codeMirror"></ZgCodeMirror>
      </a-form-item>
    </a-form>
  </div>
</template>
<script>
export default {
  props: {
    jsonStr: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      name: '',
      cata: '',
      triggerMode: ''
    }
  },
  watch: {
    jsonStr () {
      this.init()
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    onCodeMirrorLoaded (callback) {
      const ref = this.$refs.codeMirror
      if (!ref) {
        setTimeout(() => {
          this.onCodeMirrorLoaded(callback)
        }, 50)
      } else {
        callback(ref)
      }
    },
    init () {
      if (this.jsonStr && this.jsonStr.length > 0) {
        const json = JSON.parse(this.jsonStr)
        this.id = json.id
        this.name = json.name
        this.cata = json.cata
        this.triggerMode = json.triggerMode
        this.onCodeMirrorLoaded(ref => {
          ref.setVal(json.content)
        })
      }
    },
    save () {
      if (this.name.length === 0) {
        return this.$result.error('请输入公式名称')
      }
      if (this.cata.length === 0) {
        return this.$result.error('请选择公式类型')
      }
      if (this.triggerMode.length === 0) {
        return this.$result.error('请设置公式触发机制')
      }
      const content = this.$refs.codeMirror.getVal()
      if (content.length === 0) {
        return this.$result.error('请输入公式内容')
      }
      return this.$result.ok({
        id: this.id,
        name: this.name,
        cata: this.cata,
        triggerMode: this.triggerMode,
        content: content
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
